package com.system.presideover.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Calendar;
import java.util.Map;

@Slf4j
public class JWTUtilsToken {
    // 替换为您自己的密钥
    private static final String sign = "9jIWOD9idje91@#*9wofj+%5895d123";

    public static String createToken(Integer id, String username) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 7);
        SecretKey secretKey = generalKey();
        JwtBuilder builder = Jwts.builder()
                .setId(id.toString())
                .setSubject(username)
                .setIssuedAt(instance.getTime())
                .signWith(SignatureAlgorithm.HS256, secretKey);
        return builder.compact();
    }

    public static String getUserId(String token) {
        try {
            DecodedJWT verify = JWT.require(Algorithm.HMAC256(sign)).build().verify(token);
            String id = verify.getId();
            log.info("Decoded user ID: {}", id);
            return id;
        } catch (Exception e) {
            log.error("Error while decoding token: {}", e.getMessage());
            return null;
        }
    }

    public static String getToken(Map<String, String> map) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 7);
        SecretKey secretKey = generalKey();
        JwtBuilder builder = Jwts.builder()
                .setId("id")
                .setSubject("subject")
                .setIssuedAt(instance.getTime())
                .signWith(SignatureAlgorithm.HS256, secretKey);

        for (Map.Entry<String, String> entry : map.entrySet()) {
            builder.claim(entry.getKey(), entry.getValue());
        }

        return builder.compact();
    }

    public static boolean verifyToken(String token) {
        try {
            Jwts.parser().setSigningKey(sign).parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            log.error("Error while decoding token: {}", e.getMessage());
            return false;
        }
    }

    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.getEncoder().encode(sign.getBytes(StandardCharsets.UTF_8));
        return new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
    }
}
